from flask import current_app
from flask import request,jsonify
from flask import session,redirect

from Info import constants
from Info import db
from Info.constants import QINIU_DOMIN_PREFIX
from Info.models import User, Category
from Info.modules.profile import profile_blu
from flask import render_template

from Info.utils.common import get_user_info,g, send_pic
from Info.utils.response_code import RET


@profile_blu.route('/user_base')
@get_user_info
def user_base():
    user = g.user
    # 如果用户没有登录，跳转到首页
    if not user:
        return redirect('/')
    return render_template('news/user.html',user=user)

# 基本资料设置
@profile_blu.route('/user_info',methods=['POST','GET'])
@get_user_info
def user_info():
    user = g.user

    if request.method == 'GET':
        return render_template('news/user_base_info.html',user=user)

    # nick_name string 昵称
    # signature string 签名
    # gender string 性别, MAN / WOMEN
    req_dict  = request.json
    nick_name = req_dict.get('nick_name')
    signature = req_dict.get('signature')
    gender = req_dict.get('gender')

    if not user :
        redirect('/')
        return jsonify(errno=RET.USERERR,errmsg='用户未登录，不能修改基本信息')


    if not all([nick_name,signature,gender]):
        return jsonify(errno=RET.DATAERR,errmsg='缺少参数')

    if gender not in ('MAN','WOMEN'):
        return jsonify(errno=RET.DATAERR,errmsg='gender参数错误，只能为ＭＡＮ　ＯＲ　ＷＯＭＥＮ')
    # 保存数据至数据库
    # db_user = User()
    # db_user.nick_name = nick_name
    # db_user.signature = signature
    # db_user.gender = gender
    # user = User()
    user.nick_name = nick_name
    user.signature = signature
    user.gender = gender
    # db.session.add(db_user)
    try :
        db.session.commit()
    except Exception as e :
        return jsonify(errno=RET.DBERR,errmsg='保存基本信息失败')
    #
    try:
        session['nick_name'] = nick_name
    except Exception as e :
        return jsonify(errno=RET.DATAERR,errmsg='cookies 的session nick_name修改失败')

    return jsonify(errno=RET.OK,errmsg='基本信息修改成功')

# 头像设置
@profile_blu.route('/pic_info',methods=['GET','POST'])
@get_user_info
def pic_info():
    user = g.user
    if request.method == 'GET':
        return render_template('news/user_pic_info.html',user=user)
    # 接收参数：
    # avatar　ｆｉｌｅ
    try:
        avatar = request.files.get("avatar").read()
    except Exception as e :
        return jsonify(errno=RET.DATAERR,errmsg='获取头像图片数据失败')
    # 上传图片到七牛云
    try:
        url = send_pic(avatar)
    except Exception as e:
        return jsonify(errno=RET.THIRDERR,errmsg='上传图片七牛云失败')

    # user.avatar_url =  url
    user.avatar_url = 'http://pc5adepk8.bkt.clouddn.com/' + url['key']
    print(user.avatar_url)
    try :
        db.session.commit()
    except Exception as e :
        return jsonify(errno=RET.DBERR,errmsg='头像链接地址保存数据库失败')
    return jsonify(errno=RET.OK,errmsg='头像修改成功',avatar_url=user.avatar_url)

# 密码设置
@profile_blu.route('/pass_info',methods=['GET','POST'])
@get_user_info
def pass_info():
    user = g.user
    if request.method == 'GET':
        return render_template('news/user_pass_info.html')
    else:
        # 获取参数：old_password,new_password
        req_dict = request.json
        old_password = req_dict.get('old_password')
        new_password = req_dict.get('new_password')
        # 检查输入的旧密码与数据库中保存的密码是否一致
        if not user.check_passowrd(old_password):
            return jsonify(errno=RET.DATAEXIST,errmsg='输入的旧密码错误，请重新输入')

        user.password = new_password
        try:
            db.session.commit()
        except Exception as e:
            return jsonify(errno=RET.DBERR,errmsg='密码保存数据库失败')
        return jsonify(errno=RET.OK,errmsg='密码修改成功')
    
# 收藏新闻
@profile_blu.route('/collection')
@get_user_info
def collection():
    p= request.args.get('p',1)
    try:
        p = int(p)
    except Exception as e:
        p=1
        current_app.logger.error(e)

    user = g.user
    collection = []
    current_page = 1
    total_page = 1
    try :
        paginate = user.collection_news.paginate(p,constants.USER_COLLECTION_MAX_NEWS, False)
        #      获取分页数据
        collections = paginate.items
        #     获取当前页
        current_page = paginate.page
        #    获取总页数
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)

    collection_list = []
    for news in collections:
        collection_list.append(news.to_basic_dict())
    data={
        'total_page':total_page,
        'current_page':current_page,
        'collections':collection_list
    }
    return  render_template('news/user_collection.html',data=data)

# 发布新闻
@profile_blu.route('/news_release',methods=['POST','GET'])
def news_release():
    if request.method == 'GET':
        category = Category.query.filter(Category.id != 1)
        return render_template('news/user_news_release.html',category=category)
    else:
        # title         string 新闻标题
        # category_id   int    新闻分类_id
        # digest        string 新闻摘要
        # index_image   file   索引图片
        # content       string 新闻内容
        print('post')